<?php
/**
 * Date.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-22
 * Time: 13:00
 */

namespace App\Http\Controllers\Api\System;


use App\Http\Controllers\Base;
use App\Tables;

class Date extends Base
{
    public function getHasDate()
    {
        $year = (int) $this->request->get('year');
        $month = (int) $this->request->get('month');
        if($year <= 0 or $month <= 0) {
            return $this->responseSuccess();
        }
        $sD = date('Y-m-d', strtotime("{$year}-{$month}-01"));
        $eD = date('Y-m-d', strtotime("{$sD} +1 month"));
        $list = Tables\DateSchedule::whereBetween('date', [$sD, $eD])
            ->select(\DB::raw('COUNT(date) as number'), 'date')
            ->groupBy('date')
            ->get();
        return $this->responseSuccess($list->toArray());
    }

    public function getListByDate()
    {
        $year = (int) $this->request->get('year');
        $month = (int) $this->request->get('month');
        $date = (int) $this->request->get('date');
        if($year <= 0 or $month <= 0 or $date <= 0) {
            return $this->responseSuccess();
        }
        $list = Tables\DateSchedule::where('date', implode('-', [$year,$month,$date]))->get();
        return $this->responseSuccess($list->toArray());
    }

    public function add()
    {
        $date = $this->request->post('date');
        $type = (int) $this->request->post('type', 0);
        $content = $this->request->post('content');

        if(empty($date)) {
            return $this->responseFail('请选择日期');
        }
        $date = date('Y-m-d', strtotime($date));
        if($type <= 0) { return $this->responseFail('类型错误！');}
        if(empty($content)){ return $this->responseFail('请填写内容');}
        $ok = (bool) Tables\DateSchedule::insert([
            'type' => $type,
            'date' => $date,
            'content' => $content,
            'add_time' => time()
        ]);
        return $ok ? $this->responseSuccess() : $this->responseFail('增加失败');
    }

    public function del()
    {
        $id = (int) $this->request->post('id', 0);
        if($id <= 0) { return $this->responseFail('无信息'); }
        $find = Tables\DateSchedule::find($id);
        if(empty($find)) { return $this->responseFail('查询不到信息');}
        return (bool) $find->delete()  ? $this->responseSuccess() : $this->responseFail();
    }
}